package red.yancloud.www.ui.activity

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_special_topic_content.*
import kotlinx.android.synthetic.main.activity_special_topic_content.errorView
import kotlinx.android.synthetic.main.activity_special_topic_content.smartRefreshLayout
import kotlinx.android.synthetic.main.title_base_head.*
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.SpecialTopicContent
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.ui.adapter.SpecialTopicContentRecyclerAdapter
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.TimeFormatUtil
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/31 11:34
 * E_Mail：yh131412hys@163.com
 * Describe：红云专题内容
 * Change：
 * @Version：V1.0
 */
class SpecialTopicContentActivity : BaseActivity(), View.OnClickListener {

    private lateinit var id:String
    private lateinit var dataList: ArrayList<SpecialTopicContentRecyclerAdapter.MySection>

    override val layoutId: Int
        get() = R.layout.activity_special_topic_content

    override fun configViews() {

        title_tv.text = getString(R.string.content_acquisition)
        back_iv.setOnClickListener(this)

        initRecyclerView()
        initSmartRefreshLayout()
    }

    override fun initData() {

        id = intent.getStringExtra("id")
        dataList = ArrayList()
        getSpecialTopicContent()
    }

    private fun getSpecialTopicContent() {

        loadingDialog.show()

        RedCloudApis.getInstance().getSubjectTheme(id, object : Observer<SpecialTopicContent> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: SpecialTopicContent) {

                if (t.code == Constants.SYSTEM_OK && t.data != null) {

                    if (t.data.sort != null) {

                        title_tv.text= t.data.sort.title
                    }

                    dataList.clear()

                    val data = t.data
                    if (data.tanbensuyuan != null) {

                        dataList.add(SpecialTopicContentRecyclerAdapter.MySection(true, data.tanbensuyuan.title,data.tanbensuyuan.typeid.toString()))
                        if (data.tanbensuyuan.data != null && data.tanbensuyuan.data.size > 0) {

                            for (datum in data.tanbensuyuan.data) {

                                dataList.add(SpecialTopicContentRecyclerAdapter.MySection(datum))
                            }
                        }
                    }

                    if (data.mingjiajiexi != null) {

                        dataList.add(SpecialTopicContentRecyclerAdapter.MySection(true, data.mingjiajiexi.title,data.mingjiajiexi.typeid.toString()))
                        if (data.mingjiajiexi.data != null && data.mingjiajiexi.data.size > 0) {

                            for (datum in data.mingjiajiexi.data) {

                                dataList.add(
                                    SpecialTopicContentRecyclerAdapter.MySection(
                                        SpecialTopicContent.DataBeanXXX.TanbensuyuanBean.DataBean(
                                            datum.title,
                                            datum.id,
                                            datum.addtime,
                                            datum.thumbnail,
                                            datum.introduce
                                        )
                                    )
                                )
                            }
                        }
                    }

                    if (data.wenxiancaokan != null) {

                        dataList.add(SpecialTopicContentRecyclerAdapter.MySection(true, data.wenxiancaokan.title,data.wenxiancaokan.typeid.toString()))
                        if (data.wenxiancaokan.data != null && data.wenxiancaokan.data.size > 0) {

                            for (datum in data.wenxiancaokan.data) {

                                dataList.add(
                                    SpecialTopicContentRecyclerAdapter.MySection(
                                        SpecialTopicContent.DataBeanXXX.TanbensuyuanBean.DataBean(
                                            datum.title,
                                            datum.id,
                                            datum.addtime,
                                            datum.thumbnail,
                                            datum.introduce
                                        )
                                    )
                                )
                            }
                        }
                    }

                    if (dataList.size > 0) {

                        errorView.visibility = View.GONE
                        smartRefreshLayout.visibility = View.VISIBLE
                    } else {

                        errorView.visibility = View.VISIBLE
                        smartRefreshLayout.visibility = View.GONE
                    }

                    val mAdapter = SpecialTopicContentRecyclerAdapter(
                        R.layout.item_special_topic_content_title_list,
                        dataList
                    )
                    specialTopicContentActivity_rV.adapter = mAdapter
                    mAdapter.onItemChildClickListener = object : BaseQuickAdapter.OnItemChildClickListener {
                        override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                            if (view!!.id==R.id.specialTopicContentItem_more) {

                                startActivity(
                                    Intent(mContext, SpecialTopicContentMoreActivity::class.java)
                                        .putExtra("id",id)
                                        .putExtra("typeId",(mAdapter.data[position] as SpecialTopicContentRecyclerAdapter.MySection).typeId)
                                        .putExtra("title",(mAdapter.data[position] as SpecialTopicContentRecyclerAdapter.MySection).header)
                                )
                            }
                        }
                    }
                    mAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener {
                        override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                            if (mAdapter.data[position].t is SpecialTopicContent.DataBeanXXX.TanbensuyuanBean.DataBean) {

                                startActivity(
                                    Intent(this@SpecialTopicContentActivity, NewsInfoActivity::class.java)
                                        .putExtra(
                                            "url",
                                            "${Constants.API_BASE_RED_CLOUD_URL}News/index?id="+ mAdapter.data[position].t.id
                                        )
                                        .putExtra("model",Constants.CollectModel.SUBJECT)
                                        .putExtra("id",id)
                                )
                            }
                        }
                    }
                    val headView = LayoutInflater.from(mContext).inflate(R.layout.special_content_head_view, null)
                    mAdapter.addHeaderView(headView)
                    headView.findViewById<AppCompatTextView>(R.id.specialContentHeadViewItem_title_tv).text=intent.getStringExtra("introduce")
                } else {

                    errorView.visibility = View.VISIBLE
                    smartRefreshLayout.visibility = View.GONE
                }

                loadingDialog.dismiss()
                smartRefreshLayout.finishRefresh()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
                smartRefreshLayout.finishRefresh()
                errorView.visibility = View.VISIBLE
                smartRefreshLayout.visibility = View.GONE
            }
        })
    }

    private fun initRecyclerView() {

        specialTopicContentActivity_rV.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        specialTopicContentActivity_rV.addItemDecoration(
            RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
    }

    private fun initSmartRefreshLayout() {

        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(this)) {
                errorView.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            getSpecialTopicContent()
        })

        smartRefreshLayout.setEnableLoadMore(false)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> {

                finish()
            }
        }
    }
}
